/*
 * Copyright 2020-2022 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.security.oauth2.server.authorization.token;

import java.time.Instant;
import java.util.Base64;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.springframework.lang.Nullable;
import org.springframework.security.crypto.keygen.Base64StringKeyGenerator;
import org.springframework.security.crypto.keygen.StringKeyGenerator;
import org.springframework.security.oauth2.core.ClaimAccessor;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.settings.OAuth2TokenFormat;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * An {@link OAuth2TokenGenerator} that generates a
 * {@link OAuth2TokenFormat#REFERENCE "reference"} (opaque) {@link OAuth2AccessToken}.
 *
 * @author Joe Grandja
 * @since 0.2.3
 * @see OAuth2TokenGenerator
 * @see OAuth2AccessToken
 * @see OAuth2TokenCustomizer
 * @see OAuth2TokenClaimsContext
 * @see OAuth2TokenClaimsSet
 */
public final class OAuth2AccessTokenGenerator implements OAuth2TokenGenerator<OAuth2AccessToken> {
	private final StringKeyGenerator accessTokenGenerator =
			new Base64StringKeyGenerator(Base64.getUrlEncoder().withoutPadding(), 96);
	private OAuth2TokenCustomizer<OAuth2TokenClaimsContext> accessTokenCustomizer;

	@Nullable
	@Override
	public OAuth2AccessToken generate(OAuth2TokenContext context) {
		//如果需要生成的token类型不是access_token 或者生成access_token的类型不是reference而是self-contained，那么直接返回null
		if (!OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType()) ||
				!OAuth2TokenFormat.REFERENCE.equals(context.getRegisteredClient().getTokenSettings().getAccessTokenFormat())) {
			return null;
		}

		String issuer = null;
		//context.getAuthorizationServerContext()得到的为安全环境上下文，里面封装了我们配置的各个url信息，再AuthorizationServerContextFilter中初始化的
		//此处issuer即我们授权服务器的地址 http://127.0.0.1:8083/authorizationProject
		if (context.getAuthorizationServerContext() != null) {
			issuer = context.getAuthorizationServerContext().getIssuer();
		}
		//获取认证的客户端信息
		RegisteredClient registeredClient = context.getRegisteredClient();
		//token生成发出时间
		Instant issuedAt = Instant.now();
		//token失效时间 默认7200秒 2小时
		Instant expiresAt = issuedAt.plus(registeredClient.getTokenSettings().getAccessTokenTimeToLive());

		// @formatter:off
		// 创建一个OAuth2TokenClaimsSet的构造器，里面含有一个claims(声明：包含授权服务器的地址，认证用户名称，认证客户端id等信息)属性Map集合
		// 该claims集合最终会被存储到oauth2_authorization.access_token_metadata字段中
		OAuth2TokenClaimsSet.Builder claimsBuilder = OAuth2TokenClaimsSet.builder();
		if (StringUtils.hasText(issuer)) {
			//设置授权服务器地址
			claimsBuilder.issuer(issuer);
		}
		claimsBuilder
				//设置用户名
				.subject(context.getPrincipal().getName())
				//设置认证客户端id
				.audience(Collections.singletonList(registeredClient.getClientId()))
				//设置令牌生成发出时间
				.issuedAt(issuedAt)
				//设置失效时间
				.expiresAt(expiresAt)
				//设置生效时间
				.notBefore(issuedAt)
				//设置uuid
				.id(UUID.randomUUID().toString());
		if (!CollectionUtils.isEmpty(context.getAuthorizedScopes())) {
			//context.getAuthorizedScopes()最原始的客户端发起的授权请求中的scope参数
			claimsBuilder.claim(OAuth2ParameterNames.SCOPE, context.getAuthorizedScopes());
		}
		// @formatter:on
		//OAuth2TokenEndpointConfigurer配置类初始化的时候会获取容器中OAuth2TokenCustomizer的实现类泛型为OAuth2TokenClaimsContext 注入到该属性
		if (this.accessTokenCustomizer != null) {
			// @formatter:off
			OAuth2TokenClaimsContext.Builder accessTokenContextBuilder = OAuth2TokenClaimsContext.with(claimsBuilder)
					.registeredClient(context.getRegisteredClient())
					.principal(context.getPrincipal())
					.authorizationServerContext(context.getAuthorizationServerContext())
					.authorizedScopes(context.getAuthorizedScopes())
					.tokenType(context.getTokenType())
					.authorizationGrantType(context.getAuthorizationGrantType());
			if (context.getAuthorization() != null) {
				accessTokenContextBuilder.authorization(context.getAuthorization());
			}
			if (context.getAuthorizationGrant() != null) {
				accessTokenContextBuilder.authorizationGrant(context.getAuthorizationGrant());
			}
			// @formatter:on

			OAuth2TokenClaimsContext accessTokenContext = accessTokenContextBuilder.build();
			//可以对claimsBuilder中的属性进行调整
			this.accessTokenCustomizer.customize(accessTokenContext);
		}
		//构建OAuth2TokenClaimsSet对象
		OAuth2TokenClaimsSet accessTokenClaimsSet = claimsBuilder.build();
		//生成最终的OAuth2AccessToken对象，里面包括token(96位随机数 base64加密生成) token的生效和失效时间 授权范围 还有构建的claims(声明信息)
		OAuth2AccessToken accessToken = new OAuth2AccessTokenClaims(OAuth2AccessToken.TokenType.BEARER,
				this.accessTokenGenerator.generateKey(), accessTokenClaimsSet.getIssuedAt(), accessTokenClaimsSet.getExpiresAt(),
				context.getAuthorizedScopes(), accessTokenClaimsSet.getClaims());

		return accessToken;
	}

	/**
	 * Sets the {@link OAuth2TokenCustomizer} that customizes the
	 * {@link OAuth2TokenClaimsContext#getClaims() claims} for the {@link OAuth2AccessToken}.
	 *
	 * @param accessTokenCustomizer the {@link OAuth2TokenCustomizer} that customizes the claims for the {@code OAuth2AccessToken}
	 */
	public void setAccessTokenCustomizer(OAuth2TokenCustomizer<OAuth2TokenClaimsContext> accessTokenCustomizer) {
		Assert.notNull(accessTokenCustomizer, "accessTokenCustomizer cannot be null");
		this.accessTokenCustomizer = accessTokenCustomizer;
	}

	private static final class OAuth2AccessTokenClaims extends OAuth2AccessToken implements ClaimAccessor {
		private final Map<String, Object> claims;

		private OAuth2AccessTokenClaims(TokenType tokenType, String tokenValue,
				Instant issuedAt, Instant expiresAt, Set<String> scopes, Map<String, Object> claims) {
			super(tokenType, tokenValue, issuedAt, expiresAt, scopes);
			this.claims = claims;
		}

		@Override
		public Map<String, Object> getClaims() {
			return this.claims;
		}

	}

}
